import { createStore as _createStore } from 'vuex'
import {findPostList, findWeightList, getPostInfo} from "../api/post";
import {fileGet} from "../api/sys";
import {PostItem} from "../api/modules/post";
import markdown from "../utils/markdown";
import {nextTick} from "vue";

export function createStore() {
    return _createStore({
        state() {
            return {
                postList: [] as PostItem[],
                weightList: [] as PostItem[],
                postInfo: {},
                page: 1,
            }
        },
        getters: {
            getPostListData: state => {
                return state.postList;
            },
            getPostInfoData: state => {
                return state.postInfo;
            },
            getWeightListData: state => {
                return state.weightList;
            },
            getPage: state => {
                return state.page;
            },
        },
        mutations: {
            setPostList(state, data) {
                state.postList = [...state.postList, ...data.content];
            },
            updatePage(state) {
                state.page++;
            },
            setPostInfo(state, data) {
                state.postInfo = data;
            },
            setWeightList(state, data) {
                state.weightList = data.content;
            },
            setCover(state, data) {
                state.postList = data;
            },
            setWeightCover(state, data) {
                state.weightList = data;
            },
        },
        actions: {
            async getPostInfo({ commit }, id) {
                const data = await getPostInfo(id);
                if (data) {
                    commit("setPostInfo", data);
                }
            },
            async findPostList({ commit, getters }) {
                const postResp = await findPostList(null, getters.getPage);
                commit("setPostList", postResp);
            },

            async findWeightList({ commit }) {
                const weightResp = await findWeightList();
                commit("setWeightList", weightResp);
            },

            async initPost({ commit, getters, dispatch }) {
                await dispatch('findPostList');
                getters.getPostListData.forEach(async(item) => {
                    item.cover = await fileGet(1)
                })
                commit("setCover", getters.getPostListData);

                await dispatch('findWeightList');
                getters.getWeightListData.forEach(async(item) => {
                    item.cover = await fileGet(1)
                })
                commit("setWeightCover", getters.getWeightListData);
            },
        }
    })
}
